package com.tianpengcc.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.tianpengcc.dao.UserDAO;
import com.tianpengcc.model.User;
import com.tianpengcc.util.DBUtil;
import com.tianpengcc.util.MD5Util;

public class UserDAOImpl implements UserDAO {
	private Connection conn ; 
	
	@Override
	public User findByUser(User user) throws Exception {
		String userName = user.getUserName() ;
		String password = user.getPassword() ;
		if(userName == null || "".equals(userName)){
			return null ;
		}
		if(password == null || "".equals(password)){
			return null ;
		}
		this.conn = DBUtil.getConnection() ;
		password = MD5Util.md5(password) ;
		String sql = "SELECT * FROM t_user WHERE userName = ? AND password = ?" ;
		PreparedStatement ppst = conn.prepareStatement(sql);
		ppst.setString(1, userName);
		ppst.setString(2, password);
		ResultSet rs = ppst.executeQuery();
		User userResult = null ;
		if(rs.next()){
			Integer userId = rs.getInt(1) ;
			userName = rs.getString(2) ;
			password = rs.getString(3) ;
			String imagePath = rs.getString(4) ;
			String nickName = rs.getString(5) ;
			String mood = rs.getString(6) ;
			userResult = new User(userId, userName, password, imagePath, nickName, mood) ;
		}
		rs.close(); 
		ppst.close();
		DBUtil.close(conn);
		return userResult;
	}

	@Override
	public void doUpdate(Integer id, User user) throws Exception {
		this.conn = DBUtil.getConnection() ;
		String sql = "UPDATE t_user SET imagePath = ?,nickName = ?,mood = ? WHERE userId = ?" ;
		PreparedStatement ppst = conn.prepareStatement(sql);
		ppst.setString(1,user.getImagePath());
		ppst.setString(2, user.getNickName());
		ppst.setString(3, user.getMood());
		ppst.setInt(4, id);
		int record = ppst.executeUpdate();
		if(record <= 0){
			throw new Exception("用户没有修改成功！") ;
		}
		
		ppst.close();
		DBUtil.close(conn);
	}

	@Override
	public User findById(Integer userId) throws Exception {
		conn = DBUtil.getConnection() ;
		User user = null ;
		String sql = "SELECT * FROM t_user WHERE userId = ?" ;
		PreparedStatement ppst = conn.prepareStatement(sql);
		ppst.setInt(1, userId);
		ResultSet rs = ppst.executeQuery();
		if(rs.next()){
			user = new User() ;
			user.setUserId(rs.getInt(1));
			user.setUserName(rs.getString(2));
			user.setPassword(rs.getString(3));
			user.setImagePath(rs.getString(4));
			user.setNickName(rs.getString(5));
			user.setMood(rs.getString(6));
		}
		
		rs.close();
		ppst.close();
		DBUtil.close(conn);
		return user;
	}
	
}
